package org.loong.crypto.extension.cms.jce;

import java.io.InputStream;
import java.security.Key;
import java.security.PrivateKey;

import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.RecipientOperator;
import org.bouncycastle.operator.InputDecryptor;
import org.loong.crypto.extension.cms.EnvelopedDataHelper;
import org.loong.crypto.extension.cms.jce.io.CipherInputStream;
import org.loong.crypto.service.CryptoService;

public class JceKeyTransEnvelopedRecipient extends JceKeyTransRecipient {

    protected EnvelopedDataHelper helper = new EnvelopedDataHelper();

    public JceKeyTransEnvelopedRecipient(CryptoService cryptoService, PrivateKey recipientKey) {
        super(cryptoService, recipientKey);
    }
    
    public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey)
            throws CMSException {
        Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, encryptedContentEncryptionKey);
        byte[] iv = helper.getIv(secretKey, contentEncryptionAlgorithm);
        
        return new RecipientOperator(new InputDecryptor() {

            public AlgorithmIdentifier getAlgorithmIdentifier() {
                return contentEncryptionAlgorithm;
            }

            public InputStream getInputStream(InputStream dataIn) {
                return new CipherInputStream(dataIn, cryptoService, contentEncryptionAlgorithm.getAlgorithm(), secretKey, iv);
            }
        });
    }
}
